package cn.kooki.app.duobao.ui.Activity.User;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseNavActivity;
import cn.kooki.app.duobao.core.GlideCircleTransform;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.Bean.base.BaseResponse;
import cn.kooki.app.duobao.data.bus.UserRefrshEvent;
import cn.kooki.app.duobao.data.constant.Constants;
import cn.kooki.app.duobao.util.FileUtils;
import cn.kooki.app.duobao.util.ImageUtils;
import cn.kooki.app.duobao.util.PhoneCheckUtils;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;

import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
import retrofit.mime.TypedString;

/**
 * Created by xiong on 2015/12/14.
 */
public class UserinfoActivity extends BaseNavActivity implements View.OnClickListener {
    private static final int PICK_IMAGE_RECODE = 101;
    private static final int PICK_IMAGE_PHOTO = 1002;
    @Bind(R.id.iv_avatar)
    ImageView ivAvatar;
    @Bind(R.id.layout_avatar)
    RelativeLayout layoutAvatar;
    @Bind(R.id.tv_cid)
    TextView tvCid;
    @Bind(R.id.tv_uid)
    TextView tvUid;
    @Bind(R.id.tv_nickname)
    TextView tvNickname;
    @Bind(R.id.layout_nickname)
    RelativeLayout layoutNickname;
    @Bind(R.id.tv_mobile)
    TextView tvMobile;
    @Bind(R.id.layout_mobile)
    RelativeLayout layoutMobile;
    @Bind(R.id.layout_address)
    RelativeLayout layoutAddress;
    @Bind(R.id.mobile_arrow)
    ImageView mobileArrow;
    private UserInfo userinfo;
    private int PICK_IMAGE_CROP;
    private Uri imageuri;
    private String path;
    private Bitmap bitmap;

    @Override
    public void setLayoutContainerView() {
        setContainerView(R.layout.activity_profile);
        ButterKnife.bind(this);
    }

    @Override
    protected void afterView() {
        path = Constants.APP_IMG_FOLDER_PATH.toString();
        FileUtils.makeDirs(path);
        layoutAddress.setOnClickListener(this);
        setTitle(R.string.title_activity_profile);
        layoutAvatar.setOnClickListener(this);
        layoutNickname.setOnClickListener(this);
        layoutMobile.setOnClickListener(this);

        refreshuser();

    }

    private void refreshuser() {
        userinfo = SharePreferencesUtils.getUserinfo(this);

        if (!TextUtils.isEmpty(userinfo.getImg()) && bitmap == null) {
            Glide.with(this).load(userinfo.getImg()).
                    transform(new GlideCircleTransform(this)).into(ivAvatar);
        }
        tvCid.setText(userinfo.getUid());
        tvUid.setText(userinfo.getUsername());
        tvNickname.setText(userinfo.getUsername());
        if (!TextUtils.isEmpty(userinfo.getMobile())) {
            tvMobile.setText(userinfo.getMobile());
            mobileArrow.setVisibility(View.GONE);
        } else {
            mobileArrow.setVisibility(View.VISIBLE);
        }
    }


    public void onEventMainThread(UserRefrshEvent event) {
        refreshuser();
    }

    @Override
    public void onClick(View v) {
        if (v == layoutAddress) {
            intent(ShipAddressActivity.class);
        }
        if (v == layoutAvatar) {
            showpicker();
        }
        if (v == layoutNickname) {
            intent(UpdateNickNameActivity.class);
        }
        if (v == layoutMobile) {
            if (!PhoneCheckUtils.checkphone(this)) {
                intent(BindActivity.class);
            }
        }
    }

    private void showpicker() {
        new AlertDialog.Builder(this).setTitle("修改头像").setItems(new String[]{"相册", "拍照"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.i("test", which + "");
                pickerImage(which);
            }
        }).setNegativeButton("取消", null).show();
    }

    private File tempfile = null;
    private File cropfile = null;

    private void pickerImage(int which) {
        Intent intent = new Intent();

        if (which == 0) {
            PhotoPickerIntent photoPickerIntent = new PhotoPickerIntent(this);
            photoPickerIntent.setPhotoCount(1);
            photoPickerIntent.setShowCamera(false);
            photoPickerIntent.setShowGif(false);
            startActivityForResult(photoPickerIntent, PICK_IMAGE_PHOTO);
        } else {
            tempfile = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
            imageuri = Uri.fromFile(tempfile);
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageuri);
            startActivityForResult(intent, PICK_IMAGE_RECODE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == UCrop.REQUEST_CROP) {
                final Uri resultUri = UCrop.getOutput(data);
                bitmap = BitmapFactory.decodeFile(resultUri.getPath());
                uploadbitmap(bitmap);
            } else if (requestCode == PICK_IMAGE_RECODE) {

                cropImageUri(imageuri);
            } else if (requestCode == PICK_IMAGE_PHOTO) {
                ArrayList<String> photos = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                imageuri = Uri.fromFile(new File(photos.get(0)));
                cropImageUri(imageuri);
            }
        }
    }

    private void uploadbitmap(Bitmap bitmap) {
        showLoading("正在上传...");

        String tempname = "temp.jpg";
        File tempfile = new File(path + tempname);

        ImageUtils.compressBmpToFile(bitmap, tempfile);
        MainFactory.getApiInstance().userIconChange(new TypedString(userinfo.getUid()), new TypedFile("jpg", tempfile), new Callback<BaseResponse>() {
            @Override
            public void success(BaseResponse baseResponse, Response response) {
                dismissLoading();
                if (baseResponse.getStatus() == 0) {
                    EventBus.getDefault().post(new UserRefrshEvent());
                    ivAvatar.setImageBitmap(UserinfoActivity.this.bitmap);
                } else {
                    showToastMessage(baseResponse.getMsg());
                }
            }

            @Override
            public void failure(RetrofitError error) {
                dismissLoading();
                showToastMessage(error.getMessage());

            }
        });

    }

    private void cropImageUri(Uri uri) {
        cropfile = new File(path + "crop.jpg");
        Uri out = Uri.fromFile(cropfile);
        UCrop.of(uri, out)
                .withAspectRatio(1, 1)
                .withMaxResultSize(160, 160)
                .start(this);
    }


}
